
/**
 * 指令
 */
define(["jquery","core","core.service","angular.util","jquery.validator","jquery.form","jquery.uploadify","bootstrap","angular","ueditor","syntaxHighlighter"],function($,core,service,util)
{
	var directives=angular.module("directives",[]);
	
	var getModelValue=function($scope,model)
	{
		try
		{
			return eval("$scope."+model);
		}
		catch(e)
		{
			return "";
		}
	};
	
	var bind=function($scope,watchFn,func)
	{
		$scope.$watch(watchFn,function(newValue)
    	{
    		func(newValue);
    	});
	};
	
	var getIncludeElement=function(url)
	{
		return util.angular.getIncludeElement(core.System.INCLUDE_PATH+url);
	};
	
	//以原格式输出
	directives.directive("source",["$compile",function($compile)
	{
		return {
			restrict:"E",
	        replace: true,
	        link:function($scope,$element,$attrs)
	        {
	        	bind($scope,$attrs.model,function(value)
	        	{
	        		$element.html($compile("<div>"+core.parser.html(value)+"</div>")($scope));
	        	});
	        }
		}
	}]);
	
	//代码高亮
	directives.directive("pre",function()
	{
		return {
			restrict:"E",
	        link:function($scope,$element,$attrs)
	        {
	        	setTimeout(function()
	        	{
	        		SyntaxHighlighter.config.clipboardSwf=window.config.base+"syntaxHighlighter/scripts/clipboard.swf";
	        		SyntaxHighlighter.config.strings=
	        		{
						expandSource:"展开代码",
						viewSource:"查看代码",
						copyToClipboard:"复制代码",
						copyToClipboardConfirmation:"代码复制成功",
						print:"打印",
						help:"帮助",
						alert:"语法高亮\n\n",
						noBrush:"不能找到刷子:",
						brushNotHtmlScript:"刷子没有配置html-script选项",
						aboutDialog:"<div></div>"
					};
					
        			SyntaxHighlighter.highlight("",$element[0]);
	        	},100);
	        }
		}
	});
	
	//分页标签
	directives.directive("paginate",[function()
	{
		return {
	       	restrict:"E",
	        link:function($scope,$element,$attrs)
	        {
	        	bind($scope,$attrs.pn,function()
	        	{
	        		core.ui.paginate
					({
						element:$element,
						pageCount:getModelValue($scope,$attrs.pageCount),
						dataSum:getModelValue($scope,$attrs.sum),
						start:getModelValue($scope,$attrs.pn),
						url:getModelValue($scope,$attrs.url),
						click:getModelValue($scope,$attrs.click),
						onlyOneShow:getModelValue($scope,$attrs.onlyoneshow)
					});
	        	});
	        }
        };
	}]);
	
	//高亮显示关键字
	directives.directive("highlight",[function()
	{
		return {
	       	restrict:"E",
	       	replace:true,
	        link:function($scope,$element,$attrs)
	        {
	        	bind($scope,$attrs.keyword,function(keyword)
	        	{
	        		var keywords=keyword.split(" ");
	        		var value=$element.text();
	        		for(var i=0;i<keywords.length;i++)
	        			value=core.util.replace(value,keywords[i],"<span style='color:red;'><strong>"+keywords[i]+"</strong></span>");
	        		
	        		$element.html(value);
	        	});
	        }
        };
	}]);
	
	//验证标识
	directives.directive("validate",[function()
	{
		return {
	       	restrict:"A",
	        link:function($scope,$element,$attrs)
	        {
	        	var callback=$attrs["callback"];
	        	if(core.util.isBlank(callback))
	        		return;
	        	
	        	var items=$element.find("[name][name!=''][rule][rule!='']");
	        	if(items.length==0)
	        		return;
	        	
	        	var fields={};
	        	for(var i=0;i<items.length;i++)
	        	{
	        		var item=$(items[i]);
	        		fields[item.attr("name")]=item.attr("rule");
	        	}
	        	
	        	$element.validator
				({
				    fields:fields,
				    valid:function(form)
				   	{
				   		eval("$scope."+callback)($scope,form);;
				   	}
				});
	        }
        };
	}]);
	
	//编辑器
	directives.directive("editor",[function()
	{
		return {
	       	restrict:"A",
	        link:function($scope,$element,$attrs)
	        {
	        	var defaultOptions=
	        	{
	        		width:500,
	        		height:300,
	        		delay:200
	        	};
	        	
	        	var options=
	        	{
	        		width:$attrs["editorWidth"],
	        		height:$attrs["editorHeight"],
	        		delay:$attrs["delay"]
	        	};
	        	
	        	options=$.extend([],defaultOptions,options);
	        	
	        	var id="editor_id_"+Math.floor(Math.random()*(999));
	        	$element.attr("id",id);
	        	
	        	setTimeout(function()
	        	{
					var editor=UE.getEditor(id,
		        	{
		        		initialFrameWidth:options.width,
		        		initialFrameHeight:options.height
		        	});
		        	
		        	var lock=new core.util.Lock();
		        	editor.addListener("contentChange",function(value)
		        	{
		        		lock.call(function()
	        			{
		        			var content=editor.getContent();
			        		$element.val(content);
			        		
		        			//这么写可以触发ng-model的更新
		        			angular.element($element).change();
		        			$scope.$apply();
	        			});
		        	});
		        	
		        	editor.addListener("ready",function()
		        	{
		        		var setContent=function(value)
		        		{
		        			editor.setContent(core.parser.html(value));
		        		};
		        		var content=$element.val();
		        		if(core.util.isBlank(content))
		        			content="";
		        		setContent(content);
						$scope.$watch(function()
				    	{
				    		lock.call(function()
		        			{
		        				setContent($element.val());
		        			});
				    	});
					});
	        	},options.delay);
	        }
        };
	}]);
	
	//滚动监听
	directives.directive("scrollListener",[function()
	{
		return {
	       	restrict:"E",
	       	replace:true,
	        link:function($scope,$element,$attrs)
	        {
				var defaultOptions=
        		{
        			bottom:true,
        			func:null
        		};
        		
        		var options=
        		{
        			bottom:$attrs["bottom"],
        			func:$attrs["func"]
        		};
        		
        		options=$.extend([],defaultOptions,options);
        		if(core.util.isBlank(options.func))
        			return;
        		
        		var scrollFunc=function()
				{
					var isTop=core.dom.isTop(),isBottom=core.dom.isBottom();
					
					if((options.bottom && isBottom) || (!options.bottom))
						eval("$scope."+options.func+"(isTop,isBottom);");
				};
				
				$(window).bind("scroll",scrollFunc);
				
				core.util.onLocationChange(function()
				{
					$(window).unbind("scroll");
				});
        	}
        };
	}]);
	
	//定时器
	directives.directive("interval",[function()
	{
		return {
			restrict:"A",
			replace:true,
			link:function($scope,$element,$attrs)
			{
				var option=
				{
					time:$attrs["time"],
					func:$attrs["func"]
				};
				
				var callFunc=function()
				{
					eval("$scope."+option.func+";");
				};
				
				callFunc();
				var interval=setInterval(function()
				{
					callFunc();
				},option.time);
				
				core.util.onLocationChange(function()
				{
					clearInterval(interval);
					interval=null;
				});
			}
		}
	}]);
	
	//侧边栏
	directives.directive("asideFloatBar",function()
	{
		return {
			restrice:"A",
			link:function($scope,$element,$attrs)
			{
				var defaultOption=
				{
					interval:200
				};
				
				var option=
				{
					interval:$attrs["interval"]	
				};
				
				option=$.extend([],defaultOption,option);
				
				$(window).bind("scroll",function()
				{
					if(core.dom.isTop())
						$element.fadeOut(option.interval);
					else
					{
						if($element.is(":hidden"))
							$element.fadeIn(option.interval);
					}
				});
			}
		}
	});
	
	//返回顶部
	directives.directive("toTop",function()
	{
		return {
			restrice:"A",
			link:function($scope,$element,$attrs)
			{
				var defaultOption=
				{
					interval:500
				};
				
				var option=
				{
					interval:$attrs["interval"]	
				};
				
				option=$.extend([],defaultOption,option);
				
				$element.click(function()
				{
					$("html,body").animate({scrollTop: 0},option.interval);
				});
			}
		}
	});
	
	//前往底部
	directives.directive("toBottom",function()
	{
		return {
			restrice:"A",
			link:function($scope,$element,$attrs)
			{
				var defaultOption=
				{
					interval:500
				};
				
				var option=
				{
					interval:$attrs["interval"]	
				};
				
				option=$.extend([],defaultOption,option);
				
				$element.click(function()
				{
					$("html,body").animate({scrollTop: $(document).height()},option.interval);
				});
			}
		}
	});
	
	//工具提示
	directives.directive("tooltip",function()
	{
		return {
			restrice:"A",
			link:function($scope,$element,$attrs)
			{
				var defaultOption=
				{
					message:"",
					placement:"top",
					trigger:"hover"
				};
					
				bind($scope,$attrs.message,function(message)
				{
					var option=
					{
						message:message,
						placement:$attrs["placement"],
						trigger:$attrs["trigger"]
					};
					option=$.extend([],defaultOption,option);
					
					if(core.util.isBlank(option.message))
						return;
					
					$element.tooltip
					({
						title:option.message,
						placement:option.placement,
						trigger:option.trigger
					});
				});
			}
		}
	});
	
	//工具提示
	directives.directive("popover",["$compile",function($compile)
	{
		return {
			restrice:"A",
			link:function($scope,$element,$attrs)
			{
				var defaultOption=
				{
					title:"",
					placement:"top",
					trigger:"hover",
					content:"",
					html:true,
					show:false,
					hide:false
				};
					
				bind($scope,$attrs.content,function(content)
				{
					var option=
					{
						title:$attrs["title"],
						content:content,
						placement:$attrs["placement"],
						trigger:$attrs["trigger"],
						html:$attrs["html"],
						show:$attrs["show"],
						hide:$attrs["hide"]
					};
					option=$.extend([],defaultOption,option);
					
					if(core.util.isBlank(option.content) || option.hide)
						return;
					
					$element.popover
					({
						title:option.title,
						placement:option.placement,
						trigger:option.trigger,
						html:option.html,
						content:option.content
					});
					
					if(option.show)
						$element.popover("show");
				});
			}
		}
	}]);
	
	//没登录时隐藏标签内元素
	directives.directive("userLogin",function()
	{
		return {
			restrice:"A",
			link:function($scope,$element,$attrs)
			{
				service.user.getMessageByToken(function(data)
				{
					if(!core.util.isBlank(data))
						return;
					
					var message=$attrs["message"];
					if(!core.util.isBlank(message))
						$element.html("<div class='alert alert-warning'><i class='glyphicon glyphicon-exclamation-sign'></i> "+message+"</div>");
					else
						$element.hide();
				});
			}
		}
	});

	//引入页面
	directives.directive("include",["$compile",function($compile)
	{
		return {
			restrict:"E",
			replace:true,
			link:function($scope,$element,$attrs)
			{
				$element.html($compile(getIncludeElement($attrs.path))($scope));
			}
		}
	}]);
	
	//显示评论标签
	directives.directive("comment",["$rootScope",function($rootScope)
	{
		return {
			restrict:"E",
			replace:true,
			template:getIncludeElement("/comment_index.html"),
			link:function($scope,$element,$attrs)
			{
				var id=null;
				bind($scope,$attrs.id,function(temp)
				{
					if(!core.util.isBlank(id) || core.util.isBlank(temp))
						return;
					
					id=temp;
					var interval;
					$rootScope.$on(core.broadcasts.COMMENT_AFTER,function(event)
					{
						clearInterval(interval);
					});
					
					interval=setInterval(function()
					{
						$scope.$broadcast(core.broadcasts.COMMENT_BEFORE,{id:id,callback:"_comment"});
					},10);
				});
			}
		}
	}]);
	
	//上传
	directives.directive("upload",[function()
	{
		return {
			restrict:"A",
			replace:true,
			controller:function($scope,$element,$attrs)
			{
				var showUpload=function()
				{
					util.angular.dialog.baseDialog
					({
						title:"文件上传",
						path:util.getIncludePath("/upload.html"),
						showClose:false,
						moduleName:"FileUploadModule",
						controllerName:"FileUpdateController"
					},function($dialogScope,dialog)
					{
						$dialogScope.upload={uploading:false,success:false,error:null};
						
						setTimeout(function()
						{
							dialog.getInstance().find("#file").uploadify
							({
								fileObjName:"file",
								auto:true,
						        method: "POST",
						        buttonText: "选择文件",
						       	swf:core.System.STATIC_PATH+"/js/jquery/jquery.uploadify/uploadify.swf",
						        uploader:core.api.getApi(path)+"?token="+service.user.getToken(),
						        onUploadStart:function()
						        {
									$dialogScope.upload.uploading=true;
									$dialogScope.$apply();
						        },
						        onUploadSuccess: function(file, data, response)
						        {
						        	var upload=$dialogScope.upload;
						        	var result=core.message.parseResult(data);
									if(result.success)
									{
										upload.success_path=result.message;
										upload.success=true;
										upload.error=null;
										
										if(!core.util.isBlank(callback))
										{
											$scope[callback](result.message);
										}
									}
									else
									{
										upload.error=result.message;
										upload.success=false;
									}
									
									upload.uploading=false;
									$dialogScope.$apply();
						        }
							});
						},350);
						
//--old
//						$dialogScope.upload=function()
//						{
//							var upload=$dialogScope.upload;
//							upload.uploading=true;
//							$dialogScope.$apply();
//							
//							dialog.find("form").ajaxSubmit
//							({
//								url:core.api.getApi("/upload"+path)+"?token="+service.user.getToken(),
//								type:"post",
//								success:function(result)
//								{
//									result=core.message.parseResult(result);
//									if(result.success)
//									{
//										upload.success_path=result.message;
//										upload.success=true;
//										upload.error=null;
//										
//										if(!core.util.isBlank(callback))
//										{
//											$scope[callback](result.message);
//										}
//									}
//									else
//									{
//										upload.error=result.message;
//										upload.success=false;
//									}
//									
//									upload.uploading=false;
//									$dialogScope.$apply();
//								}
//							});
//						};
						
						$dialogScope.cancel=function()
						{
							dialog.close();
						};
					});
				};
				
				var path=$attrs.path;
				var callback=$attrs.callback;
				var show=$attrs.show;
				
				if(show)
					showUpload();
				
				$element.click(function()
				{
					showUpload();
				});
			}
		}
	}]);
	
	//用户资料卡标签
	directives.directive("userCard",["$rootScope",function($rootScope)
	{
		return {
			restrict:"E",
			replace:true,
			template:getIncludeElement("/user_message_card.html"),
			link:function($scope,$element,$attrs)
			{
				var defaultOption=
				{
					uid:null,
					title:null
				};
				
				var uid=null;
				bind($scope,$attrs.uid,function(temp)
				{
					if(!core.util.isBlank(uid) || core.util.isBlank(temp))
						return;
					
					uid=temp;
					var option=
					{
						uid:uid,
						title:$attrs["title"]
					};
					option=$.extend([],defaultOption,option);
					
					var interval;
					$rootScope.$on(core.broadcasts.USER_MESSAGE_CARD_AFTER,function(event)
					{
						clearInterval(interval);
					});
					
					interval=setInterval(function()
					{
						$scope.$broadcast(core.broadcasts.USER_MESSAGE_CARD_BEFORE,option);
					},10);
				});
			}
		}
	}]);
	
	//博客目录标签
	directives.directive("blogCatalogInclude",["$rootScope",function($rootScope)
	{
		return {
			restrict:"E",
			replace:true,
			template:getIncludeElement("/blog_catalog_include.html"),
			link:function($scope,$element,$attrs)
			{
				var uid=null;
				bind($scope,$attrs.uid,function(temp)
				{
					if(!core.util.isBlank(uid) || core.util.isBlank(temp))
						return;
					
					uid=temp;
					var interval;
					$rootScope.$on(core.broadcasts.BLOG_CATALOG_INCLUDE_AFTER,function(event)
					{
						clearInterval(interval);
					});
					
					interval=setInterval(function()
					{
						$scope.$broadcast(core.broadcasts.BLOG_CATALOG_INCLUDE_BEFORE,{uid:uid});
					},10);
				});
			}
		}
	}]);
});